<?php
        set_time_limit(0);
        ini_set('memory_limit', -1);

        /*
         * Crontab interface for fecthing content
         * CodeIgniter CLI http://codeigniter.com/user_guide/general/cli.html
         * 
         * $ cd /var/www/html/
         * $ php index.php cron run
         * 
         * @author Mati
         */
	class Cron extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			
                        // Libraries
                        $this->load->library('FocusLib');
                        
                        // Database
                        $this->load->database();
                        
                        // Models
			$this->load->model('users_model', 'users');
                        $this->load->model('filters_model', 'filters');
                        $this->load->model('content_model', 'content');
		}
                
                public function run()
                {
                    if($this->input->is_cli_request() || $this->focuslib->allowWebCronJob())
                    {
                        $active_filters = $this->filters->get_all();
                        
                        // For every active filter
                        foreach ($active_filters as $filter)
                        {
                            $last_fecthed = strtotime($filter->lastFetched);
                            $new_run = $last_fecthed + $filter->interval;
                                  
                            if( $new_run - time() <= 0 )
                            {
                                // Array for found content (will be delivered by email)
                                $foundContent = array();
                            
                                try
                                {
                                    // TODO: Remove
                                    var_dump('Filter title: ' . $filter->title);
                                        
                                    // Search for new content
                                    $client_filter = $this->focuslib->buildClientFilter($filter);
                                    
                                    foreach ($client_filter->filterData as $filter_data)
                                    {
                                        // TODO: Remove
                                        var_dump('Fetching for ' . $filter_data->providerName);
                                    
                                        // Instantiate provider
                                        $provider = $this->focuslib->getProvider($filter_data->providerName);

                                        // Instantiate category
                                        $category = $provider->getCategoryByID($filter_data->categoryID);
                                        
                                        // Restore last position
                                        $category->setPosition($filter_data->currentPosition);

                                        // TODO: Remove
                                        var_dump($category->getCurrentPosition());
                                        var_dump('_________________________________________________________________');
                                        
                                        while ($category->hasNext())
                                        {
                                            $next = $category->getNext();
                                            
                                            // TODO: Remove
                                            var_dump($next->title);
                                            
                                            if($provider->filter($next, $filter_data->parameters))
                                            {
                                                var_dump('Matched!');
                                                var_dump($next->getURL());
                                                
                                                // Set providerName & filterID attributes;
                                                $next->providerName = $filter_data->providerName;
                                                $next->filterID = $filter->ID;
                                                
                                                // Save to db
                                                $this->content->add($next);
                                                
                                                // Add to found content
                                                $foundContent []= $next;
                                            }
                                            else
                                            {
                                                var_dump('No match!');
                                            }
                                        }
                                        
                                        // Save the last position category reached back to filter
                                        $filter_data->currentPosition = $category->getCurrentPosition();
                                    }
                                    
                                    
                                    // Update lastFetched
                                    $filter->lastFetched = date("Y-m-d H:i:s");
                                    
                                    // Update currentPosition's
                                    $bundle = json_decode($filter->filterData);
                                    
                                    foreach ($bundle as $provider_data)
                                    {
                                        // Find item from client filter
                                        foreach ($client_filter->filterData as $filter_data)
                                        {
                                            if($filter_data->providerName == $provider_data->providerName)
                                                $provider_data->currentPosition = $filter_data->currentPosition;
                                        }
                                    }
                                    
                                    // Back to JSON
                                    $filter->filterData = json_encode($bundle);
                                    
                                    // Save
                                    $this->filters->update($filter);
                                    
                                    // Notify?
                                    if($filter->sendByEmail && count($foundContent) > 0)
                                    {
                                        // Get user profile
                                        $user = $this->users->get($client_filter->clientID);
                                        $this->focuslib->sendNotificationMessage(array(
                                            'to' => $user->email,
                                            'firstname' => $user->firstname,
                                            'lastname' => $user->lastname,
                                            'filter_title' => $filter->title
                                        ), $foundContent);
                                    }
                                    
                                     unset($foundContent);
                                     unset($client_filter);
                                }
                                catch ( Exception $exc )
                                {
                                    log_message('error', $exc->getTraceAsString());
                                } 
                                
                                // TODO: Remove
                                var_dump('_________________________________________________________________');
                            }
                        }
                    }
                    else
                    {
                        $this->output->set_status_header(403);
                        echo '
                            <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
                            <html><head>
                            <title>403 Forbidden</title>
                            </head><body>
                            <h1>Forbidden</h1>
                            <p>You don\'t have permission to access /cron on this server.</p>
                            </body></html>
                        ';
                    }
                }
        }

?>